package com.kabao.oms.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.jfinal.plugin.activerecord.Db;
import com.qianmi.open.api.DefaultOpenClient;
import com.qianmi.open.api.OpenClient;
import com.qianmi.open.api.domain.cloudshop.Item;
import com.qianmi.open.api.domain.cloudshop.Trade;
import com.qianmi.open.api.request.ItemsInventoryGetRequest;
import com.qianmi.open.api.request.ItemsOnsaleGetRequest;
import com.qianmi.open.api.request.TradesSoldGetRequest;
import com.qianmi.open.api.response.ItemsInventoryGetResponse;
import com.qianmi.open.api.response.ItemsOnsaleGetResponse;
import com.qianmi.open.api.response.TradesSoldGetResponse;


/*
 * 1、创建一个线程池，执行远程调用，并返回结果存入数据库；
 * 2、创建一个监听线程，比如1分钟时间，在55秒的时候启动，监听map里面启动的任务的状态，如果没有完成，则删除掉（远程调用的时候会有一个返回结果，根据返回结果判断是否删除，如果在存库过程中，暂时不删除，如果有问题的任务，则删除掉）
 * 3、整体的操作都是基于ConcurrentHashMap来扫描的，对其任务各个不同的状态进行扫描
 * 4、
 * 
 */

public class kbyxService {
	
	private final List<Trade> trades = new ArrayList<Trade>();
	
	private final List<Item> items = new ArrayList<Item>();
	
//	private final static OpenClient client = new DefaultOpenClient("http://gw.api.qianmi.com/api", "10000251", "rMrqdOhkh4Xal62sYS1YQq8XQaMR8jeb");
	
	public static void main(String[] args) {
		String beginDate = "2015-04-01 09:08:00";//getCurrentDateTime();//计划开始时间
		String endDate = "2015-04-27 10:08:00";//计划结束时间
		try {
			kbyxService a = new kbyxService();
			a.receiveOption(beginDate, endDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//获取当前系统时间
	private static String getCurrentDateTime(){
		String beginDate = null;
		String endDate = null;
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		beginDate = df.format(calendar.getTime());
		calendar.add(Calendar.MINUTE, -1);
		endDate = df.format(calendar.getTime());
		
		return beginDate+"#"+endDate;
	}
	
	class testThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String beginDate = "2015-04-22 09:08:00";//getCurrentDateTime();//计划开始时间
			String endDate = "2015-04-22 10:08:00";//计划结束时间
			
			StringTokenizer stringTokenizer = new StringTokenizer(kbyxService.getCurrentDateTime(),"#");
			int count = 0;
			while(stringTokenizer.hasMoreElements()){
				if(count == 0){
					endDate = stringTokenizer.nextToken();
				}else{
					beginDate = stringTokenizer.nextToken();
				}
				count++;
			}
			
			System.out.println(endDate+"__________"+beginDate);
		}
		
	}
	
	//查询接口数据的任务
    class getOrders implements Runnable{
		
		private String beginDate = "2015-04-01 09:08:00";//getCurrentDateTime();//计划开始时间
		private String endDate = "2015-04-27 10:08:00";//计划结束时间
		public void run() {
			receiveOption(beginDate, endDate);
		}
	}
    
    //获取商品信息的任务
    class getGoods implements Runnable{

    	private String beginDate = "2015-04-23 09:08:00";//getCurrentDateTime();//计划开始时间
		private String endDate = "2015-04-26 10:08:00";//计划结束时间
    	
		@Override
		public void run() {
			// TODO Auto-generated method stub
			receiveItemsOpt();
		}
    	
    }
    
    public void receiveItemsOpt(){
    	//获取当前商品信息
		try {
			receiveItems();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(items != null && items.size()> 0){//返回数据成功了，保存到数据库中
			List<String> sqlList = new ArrayList<String>();
			//解析Json，保存到数据库中
			for(Item item : items){
				//取出来，batchUpdate直接存入到数据库中
				sqlList.add("INSERT INTO t_card_goods_info (NUM_IID,SKU_ID,TITLE,PRICE,COST_PRICE,DELIVERY_TEMPLATE_ID,MODIFIED,"+ 
				"BRAND_NAME,MKT_PRICE,UNIT,TYPE_NAME,PIC_ADD) VALUES ("+item.getNumIid()+","+item.getTitle()+","+item.getPrice()+","+ 
				""+item.getCostPrice()+","+item.getDeliveryTemplateId()+","+item.getModified()+","+item.getBrandName()+","+item.getMktPrice()+","+ 
				""+item.getUnit()+","+item.getTypeName()+","+item.getPrice()+")");
			}
			Db.batch(sqlList, 1000);
			System.out.println("商品保存成功了%%%%%%%%%%%%%%%%%%%");
			//保存成功了
			trades.removeAll(trades);//删除所有的数据
			
		}
    	
    }

	
	public void receiveOption(String beginDate,String endDate){
		//获取当前时段的订单
		try {
			receiveOrder(beginDate,endDate,0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(trades != null && trades.size()> 0){//返回数据成功了，保存到数据库中
			List<String> sqlList = new ArrayList<String>();
			String sql = null;
			//解析Json，保存到数据库中
			for(Trade trade : trades){
				//取出来，batchUpdate直接存入到数据库中
				sql = "INSERT INTO t_card_orders "+
						"(TID,SELLER_NICK, PAYMENT,POST_FEE, NUM, DISCOUNT_FEE, TOTAL_FEE,TIMEOUT_ACTION_OUT,"+ 
						"REVIVER_NAME,REVIVER_STATE, REVIVER_CITY,REVIVER_DISTRICT, REVIVER_ADDRESS, REVIVER_ZIP, "+ 
						"REVIVER_MOBILE, REVIVER_PHONE, CREATED, BUYER_MESSAGE, BUYER_NICK, AREA_ID, SHIP_TYPE_ID,"+  
						"SHIP_TYPE_NAME, PAY_TYPE_ID, PAY_TYPE_NAME,TOTAL_TRADE_FEE,INVOICE_FLAG, INVOICE_TYPE, "+ 
						"USER_TYPE, IS_SUCCESS,SELL_USER_ID, SELL_USER_NAME, BUYER_NICK_NAME, ADD_USER_ID, ADD_USER_NAME,"+  
						"PAY_STATUS, DELIVER_STATUS, COMPLETE_STATUS) "+ 
						"VALUES "+ 
						"("+trade.getTid()+","+trade.getSellerNick()+","+trade.getPayment()+","+trade.getPostFee()+","+ 
						trade.getNum()+","+trade.getDiscountFee()+","+trade.getTotalFee()+","+trade.getTimeoutActionTime()+","+ 
						""+trade.getReciverName()+","+trade.getReciverState()+","+trade.getReciverCity()+","+trade.getReciverDistrict()+","+ 
						""+trade.getReciverAddress()+","+trade.getReciverZip()+","+trade.getReciverMobile()+","+trade.getReciverPhone()+","+ 
						""+trade.getCreated()+","+trade.getBuyerMessage()+","+trade.getBuyerNick()+","+trade.getAreaId()+","+trade.getShipTypeId()+","+ 
						""+trade.getShipTypeName()+","+trade.getPayTypeId()+","+trade.getPayTypeName()+","+trade.getTotalTradeFee()+","+trade.getInvoiceFlag()+","+ 
						""+trade.getInvoiceType()+","+trade.getUserType()+","+trade.getIsSuccess()+","+trade.getSaleUserId()+","+trade.getSaleUserName()+","+ 
						""+trade.getBuyerNickName()+","+trade.getAddUserId()+","+trade.getAddUserName()+","+trade.getPayStatus()+","+trade.getDeliverStatus()+","+trade.getCompleteStatus()+")";
				System.out.println(sql+"________");
				sqlList.add(sql);
			}
			Db.batch(sqlList, 1000);
			System.out.println("订单保存成功了%%%%%%%%%%%%%%%%%%%");
			//保存成功了
			trades.removeAll(trades);//删除所有的数据
			
		}
	}
	
	
	private void receiveOrder(String beginDate,String endDate,Integer pageNo) throws Exception{
		OpenClient client = new DefaultOpenClient("http://gw.api.qianmi.com/api", "10000251", "rMrqdOhkh4Xal62sYS1YQq8XQaMR8jeb");
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		req.setFields("tid,seller_nick,payment,post_fee,num,discount_fee,total_fee,timeout_action_out,reviver_name,reviver_state,reviver_city,"+
  "reviver_district,reviver_address,reviver_zip,reviver_mobile,reviver_phone,created,buyer_message,buyer_nick,area_id,ship_type_id,ship_type_name,pay_type_id,"+
  "pay_type_name,total_trade_fee,invoice_flag,invoice_type,user_type,is_success,sell_user_id,sell_user_name,buyer_nick_name,add_user_id,add_user_name,pay_status,deliver_status,complete_status");
		System.out.println(beginDate+"***"+endDate+"&&&&"+pageNo);
		req.setStartCreated(beginDate);
		req.setEndCreated(endDate);
//		req.setPayStatus("0");//获取已经支付的订单
//		req.setCompleteStatus("0");//获取正在进行中的订单
		req.setPageSize(100);//最大条数
		req.setPageNo(pageNo);
		TradesSoldGetResponse response = client.execute(req, "9542a834eace40cda20a7d0ce231cd76");

		if(response.getTrades().size() > 0){//有数据
			for(Trade trade : response.getTrades()){
				trades.add(trade);
			}
			receiveOrder(beginDate, endDate, pageNo+1);
		}
	}
	
	private void receiveItems() throws Exception{
		
		//获取仓储中的商品
		OpenClient client = new DefaultOpenClient("http://gw.api.qianmi.com/api", "10000251", "rMrqdOhkh4Xal62sYS1YQq8XQaMR8jeb");
		ItemsInventoryGetRequest req = new ItemsInventoryGetRequest();
//		req.setFields("num_iid,title,price,cost_price,delivery_template_id,modified, brand_name, mkt_price, unit, type_name");
//		req.setFields("num_iid,title,price,cost_price");
		req.setFields("cid,seller_cids,pic_url,num,list_time,delist_time,price,modified,item_imgs,approve_status,is_virtual,num_iid,title,nick,desc,props_name,created,is_fenxiao,unit,sub_stock,item_weight,item_size,outer_id,brand_id,brand_name,type_id,type_name");
		req.setTimestamp(new Date().getTime());
		req.setPageSize(100);//最大条数
		req.setPageNo(0);
		ItemsInventoryGetResponse response = client.execute(req, "9542a834eace40cda20a7d0ce231cd76");
		System.out.println(response.getItems().size()+"*****************8");
		if(response.getItems().size() > 0){//有数据
			for(Item item : response.getItems()){
				items.add(item);
			}
			receiveItems();
		}
	}
	
	private void receiveOnSaleItems() throws Exception{	
		OpenClient client = new DefaultOpenClient("http://gw.api.qianmi.com/api", "10000251", "rMrqdOhkh4Xal62sYS1YQq8XQaMR8jeb");
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("cid,seller_cids,pic_url,num,list_time,delist_time,price,modified,item_imgs,approve_status,is_virtual,num_iid,title,nick,desc,props_name,created,is_fenxiao,unit,sub_stock,item_weight,item_size,outer_id,brand_id,brand_name,type_id,type_name");
		ItemsOnsaleGetResponse response = client.execute(req, "9542a834eace40cda20a7d0ce231cd76");
		if(response.getItems().size() > 0){//有数据
			for(Item item : response.getItems()){
				items.add(item);
			}
			receiveOnSaleItems();
		}
	}
	
	
	public void schedlueMethod() throws Exception{
		ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(2);
		scheduledService.scheduleAtFixedRate(new getOrders(), 0,30, TimeUnit.MINUTES);//获取订单信息列表
//		scheduledService.scheduleAtFixedRate(new getGoods(), 0,30, TimeUnit.MINUTES);//获取商品信息列表
	}

}
